﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using PSLibrary = Microsoft.Office.Project.Server.Library;
using MSProject = Microsoft.Office.Interop.MSProject;

using DataDesign.MPP.ServerManager;
using DataDesign.MPP.Utilities;

namespace DataDesign.MPP.AddIn.Forms
{    
    public partial class FormSearchProject : Form
    {
        private static log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public MSProject.Application MSProjectApplication { get; set; }
        public MSProject.Project MSProject { get; set; }

        public string SelectedProjectName { get; private set; }

        public FormSearchProject()
        {
            InitializeComponent();
        }

        public FormSearchProject(MSProject.Application application)
        {
            MSProjectApplication = application;
            InitializeComponent();

            SetSearchDefault();
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            try
            {
                logger.Debug("BEGIN btnSearch_Click");
                dtgvProject.DataSource = ProjectManager.SearchProjectByCriteria(GetSearchCriteria());
                logger.Debug("END btnSearch_Click");
            }
            catch (Exception ex)
            {
                logger.Error("ERROR btnSearch_Click", ex);
                //throw;
                HelperAddIn.ShowError(ex.Message);
            }
        }

        private MPP.ServerManager.ObjectClass.SearchCriteria GetSearchCriteria()
        {
            try
            {
                logger.Debug("BEGIN GetSearchCriteria");
                var criteria = new ServerManager.ObjectClass.SearchCriteria();

                logger.Debug("Get text");
                if (!Common.IsNullOrWhiteSpace(txtProjectName.Text))
                    criteria.ProjectName = txtProjectName.Text;
                if (!Common.IsNullOrWhiteSpace(txtTaskName.Text))
                    criteria.TaskName = txtTaskName.Text;
                if (!Common.IsNullOrWhiteSpace(txtCustomer.Text))
                    criteria.Customer = txtCustomer.Text;
                if (!Common.IsNullOrWhiteSpace(txtResourceName.Text))
                    criteria.ResourceName = txtResourceName.Text;

                logger.Debug("Get progress");
                if (nudProgressFrom.Value > -1)
                    criteria.ProgressFrom = (int)nudProgressFrom.Value;
                if (nudProgressTo.Value > -1)
                    criteria.ProgressTo = (int)nudProgressTo.Value;                
                CheckFromTo(criteria.ProgressFrom, criteria.ProgressTo, "Progress From must be smaller than Progress To !");

                logger.Debug("Get date");
                if (!dtStartDateFrom.IsNull())
                    criteria.StartDateFrom = dtStartDateFrom.Value;
                if (!dtStartDateTo.IsNull())
                    criteria.StartDateTo = dtStartDateTo.Value;
                CheckFromTo(criteria.StartDateFrom, criteria.StartDateTo, "StartDate From must be before StartDate To !");

                if (!dtFinishDateFrom.IsNull())
                    criteria.FinishDateFrom = dtFinishDateFrom.Value;
                if (!dtFinishDateTo.IsNull())
                    criteria.FinishDateTo = dtFinishDateTo.Value;
                CheckFromTo(criteria.FinishDateFrom, criteria.FinishDateTo, "FinishDate From must be before FinishDate To !");

                logger.Debug("Get cost");
                double cost;

                if (!Common.IsNullOrWhiteSpace(txtCostFrom.Text))
                {
                    if (double.TryParse(txtCostFrom.Text, out cost))
                        criteria.CostFrom = cost;
                    else
                        throw new Exception("Cost From must be number !");
                }
                if (!Common.IsNullOrWhiteSpace(txtCostTo.Text))
                {
                    if (double.TryParse(txtCostTo.Text, out cost))
                        criteria.CostTo = cost;
                    else
                        throw new Exception("Cost To must be number !");
                }
                CheckFromTo(criteria.CostFrom, criteria.CostTo, "Cost From must be smaller than Cost To !");

                if (rdoEstimate.Checked)
                    criteria.CostType = ServerManager.ObjectClass.CostEnum.Estimate;
                else if (rdoReal.Checked)
                    criteria.CostType = ServerManager.ObjectClass.CostEnum.Real;
                else if (rdoBoth.Checked)
                    criteria.CostType = ServerManager.ObjectClass.CostEnum.Both;

                logger.Debug("END GetSearchCriteria");
                return criteria;
            }
            catch (Exception ex)
            {
                logger.Error("ERROR GetSearchCriteria", ex);
                throw;
            }
        }

        private static void CheckFromTo(IComparable from, IComparable to, string errorMessage)
        {
            if (from != null && to != null && from.CompareTo(to) >= 0)
                throw new Exception(errorMessage);
        }

        private void SetSearchDefault()
        {
            txtProjectName.Text = "";
            txtTaskName.Text = "";
            txtCustomer.Text = "";
            txtCostFrom.Text = "";
            txtCostTo.Text = "";
            txtResourceName.Text = "";

            nudProgressFrom.Value = -1;
            nudProgressFrom.ResetText();
            nudProgressTo.Value = -1;
            nudProgressTo.ResetText();

            dtStartDateFrom.SetNull();
            dtStartDateTo.SetNull();
            dtFinishDateFrom.SetNull();
            dtFinishDateTo.SetNull();

            rdoEstimate.Checked = false;
            rdoReal.Checked = false;
            rdoBoth.Checked = false;
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            SetSearchDefault();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            //detach with application
            MSProjectApplication = null;

            this.Close();
        }

        private void btnOpenProject_Click(object sender, EventArgs e)
        {
            try
            {
                if (dtgvProject.SelectedCells.Count > 0)
                {
                    string projectName = dtgvProject.Rows[dtgvProject.SelectedCells[0].RowIndex].Cells[0].Value.ToString();
                    logger.DebugFormat("projectName: {0}", projectName);
                    if (!projectName.IsServerProjectName())
                        projectName = Constant.PROJECT_NAME_ON_SERVER_PREFIX + projectName;

                    Manager.ProjectAppManager.OpenProject(MSProjectApplication, projectName); 
                }
                else
                {
                    HelperAddIn.ShowInfo("Please select project for openning !");
                }
            }
            catch (Exception ex)
            {
                logger.Error("ERROR btnOpenProject_Click", ex);
                HelperAddIn.ShowError(ex);
            }
        }
    }
}
